import { error } from "cc";

export class HttpManager{
    private static url:string="";
    
    public static getURL(path:string):string{
        return path!=null && path!="" ? `${HttpManager.url}/${path}` : path
    }
    /**
     *   fetch post 请求数据
     *   const formData = new FormData();
     *   formData.append('username', 'john_doe');
     *   formData.append('password', '123456');
     *   fetch('https://example.com/login', {
     *   method: 'POST',
     *   body: formData
     *   })
     *   .then(response => response.json())
     *   .then(data => console.log(data))
     *   .catch(error => console.error(error))
     * 
     * @param path 
     * @param data 
     * @returns 
     */
    public static post(path:string,data:any={}):Promise<any>{
        return new Promise(async resolve=>{
            const url:string=HttpManager.getURL(path);
            fetch(url,{
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(data)
            }).then(response => response.json())
            .then(result=>{resolve(result)})
            .catch(error=>{
                resolve(null)
                console.error(error)
            })
        })
    }
    public static get(path:string,data:any={}):Promise<any>{
        return new Promise(async resolve=>{
            let url:string=HttpManager.getURL(path);
            if(data){
                url+="?"
                for(let key in data){
                    url+=`${key}=${data[key]}&`
                }
                url=url.substring(0,url.length-2)
            }
            fetch(url)
            .then(response => response.json())
            .then(result => resolve(result))
            .catch(error => {
                resolve(null)
                console.error(error)
            })
        })
    }
}